package demo.service.impl;

import demo.dao.SysUserDao;
import demo.entity.SysUser;
import demo.exception.IncorrectCredentialsException;
import demo.exception.UnknownAccountException;
import demo.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.smart4j.framework.annotation.Inject;
import org.smart4j.framework.annotation.Service;

import java.util.List;

/**
 * Created by Wenxin on 2017/3/13.
 */
@Service
public class UserServiceImpl implements UserService {

    private static final Logger LOGGER = LoggerFactory.getLogger(UserServiceImpl.class);

    @Inject
    private SysUserDao sysUserDao;

    @Override
    public SysUser login(String username, String password) {

        SysUser sysUser = sysUserDao.query(username);
        if (sysUser == null) {
            throw new UnknownAccountException("login failure!");
        }
        if (!password.equals(sysUser.getPassword())) {
            throw new IncorrectCredentialsException("login failure!");
        }
        return sysUser;
    }

    @Override
    public boolean updatePassword(long id, String newPassword, String oldPasswod) {
        SysUser sysUser = sysUserDao.query(id);
        if (!oldPasswod.equals(sysUser.getPassword().trim()))
            throw new IncorrectCredentialsException("update failure!");
        int i = sysUserDao.update(newPassword, id);
        return i > 0;
    }

    @Override
    public boolean addUser(SysUser sysUser) {
        try {
            int insert = sysUserDao.insert(sysUser.getUsername(), sysUser.getPassword());
            return insert > 0;
        } catch (Exception e) {
            LOGGER.debug("insert user failure",e);
            return false;
        }
    }

    @Override
    public boolean delete(long id) {
        int delete = sysUserDao.delete(id);
        return delete > 0;
    }

    @Override
    public List<SysUser> queryList(int start, int size) {
        List<SysUser> sysUsers = sysUserDao.queryList(start, size);
        return sysUsers;
    }

    @Override
    public SysUser query(long id) {
        return sysUserDao.query(id);
    }
}
